package com.whut.manage.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.hitsdb.client.HiTSDB;
import com.aliyun.hitsdb.client.value.request.LastPointQuery;
import com.aliyun.hitsdb.client.value.request.LastPointSubQuery;
import com.aliyun.hitsdb.client.value.request.MultiFieldQuery;
import com.aliyun.hitsdb.client.value.response.LastDataValue;
import com.aliyun.hitsdb.client.value.response.MultiFieldQueryLastResult;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.whut.manage.utils.TSDBUtil;
import jdk.nashorn.internal.ir.ReturnNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
@Slf4j
@Service
public class TSDBRealTimeUpdateService {

    private static HiTSDB tsdb = TSDBUtil.getHiTSDB();
    private static SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     *设备的实时基础数据方法
     * @param name
     * @return {{@link JSONObject}}
     * @author WZH
     * @date 2021/6/9 22:10
     */
    public JSONObject DeviceBasicRealTime(String name,String value) {
        JSONObject resultobject=new JSONObject();
        long notime=System.currentTimeMillis();
        Map<String,String> tags=new HashMap<>();
        tags.put(name,value);
        //创建多个子查询
        LastPointQuery query=LastPointQuery.builder()
                .timestamp(notime).backScan(-1).msResolution(true)
                .sub(LastPointSubQuery.builder("total",tags).build())
                .sub(LastPointSubQuery.builder("deviceName",tags).build())
                .sub(LastPointSubQuery.builder("datatime",tags).build())
                .sub(LastPointSubQuery.builder("deviceType",tags).build())
                .sub(LastPointSubQuery.builder("deliverSpeed",tags).build())
                .sub(LastPointSubQuery.builder("rollerSpeed",tags).build())
                .build();
        List<LastDataValue> lastDataValues = tsdb.queryLast(query);
//        System.out.println(lastDataValues);
        lastDataValues.sort(new Comparator<LastDataValue>() {
            @Override
            public int compare(LastDataValue o1, LastDataValue o2) {
                long o1time=o1.getTimestamp();
                long o2time=o2.getTimestamp();
                if (o1time<o2time){ return -1; }
                else if (o1time>o2time){ return 1; }
                else { return 0; }
            }
        });

        //拼接json字符串
        JSONObject deviceNameobj=new JSONObject();
        JSONObject datatimeobj=new JSONObject();
        JSONObject deviceTypeobj=new JSONObject();
        JSONObject deliverSpeedobj=new JSONObject();
        JSONObject rollerSpeedobj=new JSONObject();
        JSONObject totalobj=new JSONObject();
        for (LastDataValue lastDataValue:lastDataValues) {
            if (lastDataValue.getMetric().equals("deviceName")){
                deviceNameobj.put("value",lastDataValue.getValue());
                deviceNameobj.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("deviceName",deviceNameobj);
            }
            else   if (lastDataValue.getMetric().equals("datatime")){
                datatimeobj.put("value",lastDataValue.getValue());
                datatimeobj.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("datatime",datatimeobj);
            } else   if (lastDataValue.getMetric().equals("deviceType")){
                deviceTypeobj.put("value",lastDataValue.getValue());
                deviceTypeobj.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("deviceType",deviceTypeobj);
            } else   if (lastDataValue.getMetric().equals("deliverSpeed")){
                deliverSpeedobj.put("value",lastDataValue.getValue());
                deliverSpeedobj.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("deliverSpeed",deliverSpeedobj);
            } else   if (lastDataValue.getMetric().equals("rollerSpeed")){
                rollerSpeedobj.put("value",lastDataValue.getValue());
                rollerSpeedobj.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("rollerSpeed",rollerSpeedobj);
            } else   if (lastDataValue.getMetric().equals("total")){
                totalobj.put("value",lastDataValue.getValue());
                totalobj.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("total",totalobj);
            }
        }
//        log.info("基础信息为："+resultobject);
        return resultobject;
    }


    /**
     *设备的实时产量数据服务方法
     * @param name
     * @return {{@link JSONObject}}
     * @author WZH
     * @date 2021/6/9 22:10
     */
    public JSONObject DeviceProductionRealTime(String name,String value) {
        JSONObject resultobject=new JSONObject();
        long notime=System.currentTimeMillis();
        Map<String,String> tags=new HashMap<>();
        tags.put(name,value);
        LastPointQuery query=LastPointQuery.builder()
                .timestamp(notime).backScan(-1).msResolution(true)
                .sub(LastPointSubQuery.builder("aShift",tags).build())
                .sub(LastPointSubQuery.builder("bShift",tags).build())
                .sub(LastPointSubQuery.builder("cShift",tags).build())
                .sub(LastPointSubQuery.builder("dShift",tags).build())
                .sub(LastPointSubQuery.builder("total",tags).build())
                .build();
        List<LastDataValue> lastDataValues = tsdb.queryLast(query);
        lastDataValues.sort(new Comparator<LastDataValue>() {
            @Override
            public int compare(LastDataValue o1, LastDataValue o2) {
                long o1time=o1.getTimestamp();
                long o2time=o2.getTimestamp();
                if (o1time < o2time){ return -1; }
                else if (o1time > o2time){ return 1; }
                else { return 0; }
            }
        });
        JSONObject aShfit=new JSONObject();
        JSONObject bShift=new JSONObject();
        JSONObject cShift=new JSONObject();
        JSONObject dShift=new JSONObject();
        JSONObject totalobj=new JSONObject();
        for (LastDataValue lastDataValue:lastDataValues) {
//            log.info("产量信息lastDataValue"+lastDataValue);
            if (lastDataValue.getMetric().equals("aShift")){
                aShfit.put("value",lastDataValue.getValue());
                aShfit.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("aShift",aShfit);
            }
            else   if (lastDataValue.getMetric().equals("bShift")){
                bShift.put("value",lastDataValue.getValue());
                bShift.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("bShift",bShift);
            } else   if (lastDataValue.getMetric().equals("cShift")){
                cShift.put("value",lastDataValue.getValue());
                cShift.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("cShift",cShift);
            } else   if (lastDataValue.getMetric().equals("dShift")){
                dShift.put("value",lastDataValue.getValue());
                dShift.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("dShift",dShift);
            }else   if (lastDataValue.getMetric().equals("total")){
                totalobj.put("value",lastDataValue.getValue());
                totalobj.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("total",totalobj);
            }
        }
//        log.info("产量信息为："+resultobject);
        return resultobject;
    }


    /**
     *设备的实时波谱图服务方法
     * @param name
     * @return {{@link JSONObject}}
     * @author WZH
     * @date 2021/6/9 22:09
     */
    public JSONObject DeviceWaveRealTime(String name,String value) {
        JSONObject resultobject=new JSONObject();
        long notime=System.currentTimeMillis();
        Map<String,String> tags=new HashMap<>();
        tags.put(name,value);
        //创建多个子查询
        LastPointQuery query=LastPointQuery.builder()
                .timestamp(notime).backScan(-1).msResolution(true)
                .sub(LastPointSubQuery.builder("A_wave_spectrogram",tags).build())
                .sub(LastPointSubQuery.builder("B_wave_spectrogram",tags).build())

                .build();
        List<LastDataValue> lastDataValues = tsdb.queryLast(query);
//        System.out.println(lastDataValues);
        lastDataValues.sort(new Comparator<LastDataValue>() {
            @Override
            public int compare(LastDataValue o1, LastDataValue o2) {
                long o1time=o1.getTimestamp();
                long o2time=o2.getTimestamp();
                if (o1time<o2time){ return -1; }
                else if (o1time>o2time){ return 1; }
                else { return 0; }
            }
        });

        //拼接json字符串
        JSONObject aWaveobj=new JSONObject();
        JSONObject bWaveobj=new JSONObject();

        JSONObject totalobj=new JSONObject();
        for (LastDataValue lastDataValue:lastDataValues) {
//            log.info("lastDataValue"+lastDataValue);
            if (lastDataValue.getMetric().equals("A_wave_spectrogram")){
                aWaveobj.put("value",lastDataValue.getValue());
                aWaveobj.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("A_wave_spectrogram",aWaveobj);
            }
            else   if (lastDataValue.getMetric().equals("B_wave_spectrogram")){
                bWaveobj.put("value",lastDataValue.getValue());
                bWaveobj.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("B_wave_spectrogram",bWaveobj);
            }
        }
//        log.info("波谱图信息为："+resultobject);
        return resultobject;
    }


     /**
      *设备的实时粗节数据
      * @param name
      * @return {{@link com.alibaba.fastjson.JSONObject}}
      * @author WZH
      * @date 2021/6/9 22:09
      */
    public JSONObject DeviceSlub2HRealTime(String name,String value) {
        JSONObject resultobject=new JSONObject();
        long notime=System.currentTimeMillis();
        Map<String,String> tags=new HashMap<>();
        tags.put(name,value);
        //创建多个子查询
        LastPointQuery query=LastPointQuery.builder()
                .timestamp(notime).backScan(-1).msResolution(true)
                .sub(LastPointSubQuery.builder("slub_yarn_2H_l",tags).build())
                .sub(LastPointSubQuery.builder("slub_yarn_2H_r",tags).build())
                .sub(LastPointSubQuery.builder("slub_yarn_4H1_l",tags).build())
                .sub(LastPointSubQuery.builder("slub_yarn_4H1_r",tags).build())
                .sub(LastPointSubQuery.builder("slub_yarn_4H2_l",tags).build())
                .sub(LastPointSubQuery.builder("slub_yarn_4H2_r",tags).build())
                .sub(LastPointSubQuery.builder("slub_yarn_recent_l",tags).build())
                .sub(LastPointSubQuery.builder("slub_yarn_recent_r",tags).build())
                .build();
        List<LastDataValue> lastDataValues = tsdb.queryLast(query);
        lastDataValues.sort(new Comparator<LastDataValue>() {
            @Override
            public int compare(LastDataValue o1, LastDataValue o2) {
                long o1time=o1.getTimestamp();
                long o2time=o2.getTimestamp();
                if (o1time<o2time){ return -1; }
                else if (o1time>o2time){ return 1; }
                else { return 0; }
            }
        });
        JSONObject slub_yarn_2H_l=new JSONObject();
        JSONObject slub_yarn_2H_r=new JSONObject();
        JSONObject slub_yarn_4H1_l=new JSONObject();
        JSONObject slub_yarn_4H1_r=new JSONObject();
        JSONObject slub_yarn_4H2_l=new JSONObject();
        JSONObject slub_yarn_4H2_r=new JSONObject();
        JSONObject slub_yarn_recent_l=new JSONObject();
        JSONObject slub_yarn_recent_r=new JSONObject();
        for (LastDataValue lastDataValue : lastDataValues) {
//            System.out.println(lastDataValue);
            if (lastDataValue.getMetric().equals("slub_yarn_2H_l")) {
                slub_yarn_2H_l.put("timestamp", simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                slub_yarn_2H_l.put("value", lastDataValue.getValue());
                resultobject.put("slub_yarn_2H_l", slub_yarn_2H_l);
            }else if(lastDataValue.getMetric().equals("slub_yarn_2H_r")){
                slub_yarn_2H_r.put("timestamp", simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                slub_yarn_2H_r.put("value", lastDataValue.getValue());
                resultobject.put("slub_yarn_2H_r", slub_yarn_2H_r);
            }else if(lastDataValue.getMetric().equals("slub_yarn_4H1_l")){
                slub_yarn_4H1_l.put("timestamp", simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                slub_yarn_4H1_l.put("value", lastDataValue.getValue());
                resultobject.put("slub_yarn_4H1_l", slub_yarn_4H1_l);
            }else if(lastDataValue.getMetric().equals("slub_yarn_4H1_r")){
                slub_yarn_4H1_r.put("timestamp", simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                slub_yarn_4H1_r.put("value", lastDataValue.getValue());
                resultobject.put("slub_yarn_4H1_r", slub_yarn_4H1_r);
            }else if(lastDataValue.getMetric().equals("slub_yarn_recent_r")){
                slub_yarn_recent_r.put("timestamp", simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                slub_yarn_recent_r.put("value", lastDataValue.getValue());
                resultobject.put("slub_yarn_recent_r", slub_yarn_recent_r);
            }else if(lastDataValue.getMetric().equals("slub_yarn_recent_l")){
                slub_yarn_recent_l.put("timestamp", simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                slub_yarn_recent_l.put("value", lastDataValue.getValue());
                resultobject.put("slub_yarn_recent_l", slub_yarn_recent_l);
            }else if(lastDataValue.getMetric().equals("slub_yarn_4H2_l")){
                slub_yarn_4H2_l.put("timestamp", simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                slub_yarn_4H2_l.put("value", lastDataValue.getValue());
                resultobject.put("slub_yarn_4H2_l", slub_yarn_4H2_l);
            }else if(lastDataValue.getMetric().equals("slub_yarn_4H2_r")){
                slub_yarn_4H2_r.put("timestamp", simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                slub_yarn_4H2_r.put("value", lastDataValue.getValue());
                resultobject.put("slub_yarn_4H2_r", slub_yarn_4H2_r);
            }
        }
//        log.info("基础信息为："+resultobject);
        return resultobject;
    }


    /**
     *查询设备中的质量数据

     * @return {{@link JSONObject}}
     * @author WZH
     * @date 2021/6/9 22:16
     */
    public JSONObject DeviceQualityRealTime(String name,String value) {
//        log.info("有设备访问模拟质量数据");
        JSONObject resultobject=new JSONObject();
        long notime=System.currentTimeMillis();
        Map<String,String> tags=new HashMap<>();
        tags.put(name,value);
        LastPointQuery query=LastPointQuery.builder()
                .timestamp(notime).backScan(-1).msResolution(true)
                .sub(LastPointSubQuery.builder("a_l",tags).build())
                .sub(LastPointSubQuery.builder("cv_l",tags).build())
                .sub(LastPointSubQuery.builder("cv1m_l",tags).build())
                .sub(LastPointSubQuery.builder("cv5m_l",tags).build())
                .sub(LastPointSubQuery.builder("a_r",tags).build())
                .sub(LastPointSubQuery.builder("cv_r",tags).build())
                .sub(LastPointSubQuery.builder("cv1m_r",tags).build())
                .sub(LastPointSubQuery.builder("cv5m_r",tags).build())
                .sub(LastPointSubQuery.builder("d_r",tags).build())
                .sub(LastPointSubQuery.builder("d_l",tags).build())
                .build();
        List<LastDataValue> lastDataValues = tsdb.queryLast(query);
//        log.info("模拟质量数据查询结果"+lastDataValues);
        lastDataValues.sort(new Comparator<LastDataValue>() {
            @Override
            public int compare(LastDataValue o1, LastDataValue o2) {
                long o1time=o1.getTimestamp();
                long o2time=o2.getTimestamp();
                if (o1time < o2time){ return -1; }
                else if (o1time > o2time){ return 1; }
                else { return 0; }
            }
        });

        JSONObject a_l=new JSONObject();
        JSONObject cv_l=new JSONObject();
        JSONObject cv1m_l=new JSONObject();
        JSONObject cv5m_l=new JSONObject();
        JSONObject a_r=new JSONObject();
        JSONObject cv_r=new JSONObject();
        JSONObject cv1m_r=new JSONObject();
        JSONObject cv5m_r=new JSONObject();
        JSONObject d_l=new JSONObject();
        JSONObject d_r=new JSONObject();

        for (LastDataValue lastDataValue:lastDataValues) {
//            log.info("模拟设备的质量数据:"+lastDataValue);
            if (lastDataValue.getMetric().equals("a_l")){
                a_l.put("value",lastDataValue.getValue());
                a_l.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("a_l",a_l);
            }
            else   if (lastDataValue.getMetric().equals("cv_l")){
                cv_l.put("value",lastDataValue.getValue());
                cv_l.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("cv_l",cv_l);
            } else   if (lastDataValue.getMetric().equals("cv1m_l")){
                cv1m_l.put("value",lastDataValue.getValue());
                cv1m_l.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("cv1m_l",cv1m_l);
            } else   if (lastDataValue.getMetric().equals("cv5m_l")){
                cv5m_l.put("value",lastDataValue.getValue());
                cv5m_l.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("cv5m_l",cv5m_l);
            } else   if (lastDataValue.getMetric().equals("a_r")) {
                a_r.put("value", lastDataValue.getValue());
                a_r.put("timestamp", simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("a_r", a_r);
            }else   if (lastDataValue.getMetric().equals("cv_r")){
                cv_r.put("value",lastDataValue.getValue());
                cv_r.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("cv_r",cv_r);
            } else   if (lastDataValue.getMetric().equals("cv1m_r")){
                cv1m_r.put("value",lastDataValue.getValue());
                cv1m_r.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("cv1m_r",cv1m_r);
            } else   if (lastDataValue.getMetric().equals("cv5m_r")){
                cv5m_r.put("value",lastDataValue.getValue());
                cv5m_r.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("cv5m_r",cv5m_r);
            }
            else   if (lastDataValue.getMetric().equals("d_l")){
                d_l.put("value",lastDataValue.getValue());
                d_l.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("d_l",d_l);
            }
            else   if (lastDataValue.getMetric().equals("d_r")){
                d_r.put("value",lastDataValue.getValue());
                d_r.put("timestamp",simpleDateFormat.format(new Date(lastDataValue.getTimestamp())));
                resultobject.put("d_r",d_r);
            }
        }
//        log.info("产量信息为："+resultobject);
        return resultobject;

    }


}
